package keni.html.android.framework.metadata;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import keni.html.android.framework.util.Constants;
import keni.html.android.framework.util.IVertex;
import keni.html.android.framework.util.NamedGraphNode;
import keni.html.android.framework.util.TopologicalSortAlgo;

public class FieldContainer extends ElementBase {
	
	Map<String,FieldMetadata> indexableFields=new Hashtable<String,FieldMetadata>();
	private Map<String, DataModel> dataModels=new Hashtable<String, DataModel>();
	List<DataModel> orderedDataModels=new ArrayList<DataModel>();
	DataModel dataModel=null;
	
	public DataModel getDataModel() {
		return dataModel;
	}
	
	private void mapToDataSource() {
		for (Map.Entry<String, FieldMetadata> fieldEntry : indexableFields.entrySet()) {
			FieldMetadata field=fieldEntry.getValue();
			if(!dataModels.containsKey(field.getDataSourceName()))
			{ 
				DataModel tempDataMode=new DataModel();
				tempDataMode.dataSourceName=field.getDataSourceName();
				dataModels.put(field.getDataSourceName(), tempDataMode);
			}
			DataModel dataModel=dataModels.get(field.getDataSourceName());
			dataModel.fields.add(field);
			if(field.getIsAssociateKey()){
			dataModel.parentDataSourceNames.add(field.getBelongTo());
			}
		}
		
	}
	
	 @Override
	public JSONObject convertToJsonObject() throws JSONException {
		JSONObject jsonObject=super.convertToJsonObject();
		JSONArray fieldJsonArray=new JSONArray();
		
		for (FieldMetadata fieldMetadata : getFields()) {
			fieldJsonArray.put(fieldMetadata.convertToJsonObject());
		}
		
		jsonObject.put(Constants.JsonObjectKeys.FIELDS, fieldJsonArray);

		return jsonObject;
	}
	
	void setFields(FieldMetadata fieldMetadata)
	{
		indexableFields.put(fieldMetadata.getElementId(), fieldMetadata);
	}
	
	public List<FieldMetadata> getFields() {
		List<FieldMetadata> fields=new ArrayList<FieldMetadata>();
		for (Map.Entry<String, FieldMetadata> entry : indexableFields.entrySet()) {
			fields.add(entry.getValue());
		}
		return fields;
	}
	

}
